package com.example.EL;

import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;


/**
 * @author kongwg
 * @create 2021-01-25 9:54
 */
@WebServlet("/dowload")
public class Dowload extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String img = "中国.png";

        ServletContext context = getServletContext();
        String mimeType = context.getMimeType("/img/" + img);
        System.out.println(mimeType);
        resp.setContentType(mimeType);



//  resp.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?" + new BASE64Encoder().encode(img.getBytes("UTF-8")) + "?=");


        resp.setHeader("Content-Disposition" ,"attachment");

        InputStream is = context.getResourceAsStream("/img/" + img);
        OutputStream os = resp.getOutputStream();
        IOUtils.copy(is,os);


//        String img = "中国.png";
//        ServletContext context = getServletContext();
//        String mimeType = context.getMimeType("/img/" + img);
//
//        System.out.println(mimeType);
//        resp.setContentType(mimeType);
//
//        if (req.getHeader("User-Agent").contains("Firefox")) {
//            // 如果是火狐浏览器使用Base64编码
//            resp.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?" + new BASE64Encoder().encode(img.getBytes("UTF-8")) + "?=");
//        } else {
//            // 如果不是火狐，是IE或谷歌，使用URL编码操作
//            resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(img, "UTF-8"));
//        }
//        InputStream is = context.getResourceAsStream("/img/" + img);
//        OutputStream os = resp.getOutputStream();
//        IOUtils.copy(is, os);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
